package com.alexgaoyh.MutiModule.web.demo;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.MutiModule.common.utils.JSONUtilss;
import com.MutiModule.common.utils.PaginationUtil;
import com.MutiModule.common.utils.StringUtilss;
import com.MutiModule.common.vo.EasyUIData;
import com.MutiModule.common.vo.Pagination;
import com.MutiModule.common.vo.Result;
import com.MutiModule.common.vo.enums.DeleteFlagEnum;
import com.MutiModule.common.vo.mybatis.pagination.Page;
import com.alexgaoyh.MutiModule.persist.demo.Demo;
import com.alexgaoyh.MutiModule.persist.demo.DemoExample;
import com.alexgaoyh.MutiModule.service.demo.IDemoService;
import com.alexgaoyh.MutiModule.web.util.ConstantsUtil;

@Controller
@RequestMapping(value="demo/_blank")
public class DemoController {
	
	Logger logger = LoggerFactory.getLogger(DemoController.class);
	
	@Resource
	private IDemoService demoService;
	
	/**	通用方法
	 * 后台list页面
	 * 如请求地址为：   	http://localhost:8080/web/sysmanRole/list
	 * 则返回的页面应该在    /web/WEB-INF/views/sysmanRole/list.jsp
	 * @return
	 */
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	public ModelAndView list(ModelAndView model) {
		RequestMapping rm = this.getClass().getAnnotation(RequestMapping.class);
		String moduleName = "";
		if (rm != null) {
			String[] values = rm.value();
			if (ArrayUtils.isNotEmpty(values)) {
				moduleName = values[0];
			}
		}
		if (moduleName.endsWith("/")) {
			moduleName = moduleName.substring(0, moduleName.length() - 1);
		}
		
		model.setViewName(moduleName + "/list");
		model.addObject("moduleName", moduleName);
		model.addObject("deleteFlagEnum", DeleteFlagEnum.values());
		
		return model;
	}
	
	/**
	 * 添加，弹出新页面
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/add", method = RequestMethod.GET)
	public ModelAndView add(ModelAndView model) {
		RequestMapping rm = this.getClass().getAnnotation(RequestMapping.class);
		String moduleName = "";
		if (rm != null) {
			String[] values = rm.value();
			if (ArrayUtils.isNotEmpty(values)) {
				moduleName = values[0];
			}
		}
		if (moduleName.endsWith("/")) {
			moduleName = moduleName.substring(0, moduleName.length() - 1);
		}
		
		model.setViewName(moduleName + "/add");
		model.addObject("moduleName", moduleName);
		return model;
	}
	
	/**
	 * 修改，弹出新页面
	 * @param model
	 * @return
	 * @throws IOException 
	 */
	@RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
	public ModelAndView edit(@PathVariable("id") Integer id, ModelAndView model) throws IOException {
		
		RequestMapping rm = this.getClass().getAnnotation(RequestMapping.class);
		String moduleName = "";
		if (rm != null) {
			String[] values = rm.value();
			if (ArrayUtils.isNotEmpty(values)) {
				moduleName = values[0];
			}
		}
		if (moduleName.endsWith("/")) {
			moduleName = moduleName.substring(0, moduleName.length() - 1);
		}
		
		model.setViewName(moduleName + "/edit");
		model.addObject("moduleName", moduleName);
		
		model.addObject("editId", id);
		
		return model;
	}
	
	@RequestMapping(value="selectByPrimaryKey/{id}")
    @ResponseBody
	public void selectByPrimaryKey(@PathVariable("id") Integer id, 
			HttpServletRequest request, HttpServletResponse response) throws IOException {
		Demo object = demoService.selectByPrimaryKey(id);
		JSONUtilss.renderJson(object, response);
	}
	
	/** 通用方法
	 * 后台页面渲染easyui-datagrid 方法
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping(value="getData")
    @ResponseBody
	public void getData(HttpServletRequest request, HttpServletResponse response) throws Exception {
		
		
		DemoExample exampleForCount = this.encloseObjectForCount(request);
		DemoExample exampleForList = this.encloseObjectForList(request);
		
		
		Pagination<Demo> pagination = demoService.getPanigationByRowBounds(exampleForCount, exampleForList);
		
		EasyUIData data = new EasyUIData(pagination);
		
		JSONUtilss.renderJson(data, response);
	}
	
	/** 通用方法
	 * 根据入参封装对象
	 * @param request 请求对象
	 * @return 请求对象包含的所有过滤条件进行过滤
	 */
	private DemoExample encloseObjectForCount(HttpServletRequest request) {
		DemoExample example = new DemoExample();
		
		criteriaConditions(request, example);
		
		return example;
	}
	
	/** 通用方法
	 * 根据入参封装对象
	 * @param request 请求对象
	 * @return 请求对象包含的所有过滤条件进行过滤
	 */
	private DemoExample encloseObjectForList(HttpServletRequest request) {
		DemoExample example = new DemoExample();
		
		criteriaConditions(request, example);
		
		example.setOrderByClause("id asc");
		
		Integer pageNumber = Integer.parseInt(request.getParameter("page"));//easyui datagrid 分页 页号
		Integer pageSize = Integer.parseInt(request.getParameter("rows"));//easyui datagrid 分页 页数
		Page page = new Page(PaginationUtil.startValue(pageNumber, pageSize), pageSize);
		example.setPage(page);
		
		return example;
	}
	
	private DemoExample criteriaConditions(HttpServletRequest request, DemoExample example) {
		//TODO 过滤条件筛选，后期可根据需求手动书写
		
		String searchName = request.getParameter("searchName");
		
		if(StringUtilss.isNotEmpty(searchName)) {
			example.or().andNameLike("%" + searchName + "%");
		}
		
		return example;
	}
	
	/** 通用方法 
	 * 新增，保存
	 * @param request
	 * @param response
	 * @param bean 请求对象的bean
	 * @return
	 * @throws Exception 
	 */
	@RequestMapping(value="doSave")
    @ResponseBody
	public String save(HttpServletRequest request, HttpServletResponse response, Demo entity) throws Exception {
		Result result = null;
		try {
			beforeDoSave(request, entity);
			demoService.insert(entity);
			afterDoSave(request, entity);
			result = new Result(true, "保存成功！");
		} catch (Exception e) {
			result = new Result(false, "保存失败！"+e.getMessage());
		} finally {
			JSONUtilss.renderJson(result, response);
		}

		return null;
	}
	
	/** 通用方法 
	 * 调用保存方法之前进行的方法调用
	 * @param request
	 * @param entity 对应实体信息
	 * @throws Exception
	 */
	protected void beforeDoSave(HttpServletRequest request, Demo entity) throws Exception {
		entity.setDeleteFlag(DeleteFlagEnum.NORMAL);
		entity.setCreateTime(new Date());
	}
	
	/** 通用方法 
	 * 电泳保存方法之后进行的方法调用
	 * @param request
	 * @param entity 对应实体信息
	 * @throws Exception
	 */
	protected void afterDoSave(HttpServletRequest request, Demo entity) throws Exception {
		
	}
	
	/**
	 * 更新
	 * 
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value="doUpdate")
    @ResponseBody
	public String doUpdate(HttpServletRequest request, HttpServletResponse response, Demo entity) throws IOException {
		Result result = null;
		try {
			beforeDoUpdate(request, entity);
			demoService.updateByPrimaryKeySelective(entity);
			afterDoUpdate(request, entity);
			result = new Result(true, "更新成功！");
		} catch (Exception e) {
			result = new Result(false, "更新失败！"+e.getMessage());
		} finally {
			JSONUtilss.renderJson(result, response);
		}
		return null;
	}

	/**
	 * 调用更新操作之前进行的操作
	 * @param request
	 * @param entity
	 * @throws Exception
	 */
	protected void beforeDoUpdate(HttpServletRequest request, Demo entity) throws Exception {
		
	}
	
	/**
	 * 调用更新操作之后进行的操作
	 * @param request
	 * @param entity
	 * @throws Exception
	 */
	protected void afterDoUpdate(HttpServletRequest request, Demo entity) throws Exception {
		
	}
	
	/** 通用方法 
	 * 删除
	 * @param request
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value="logicDelete")
    @ResponseBody
	public String logicDelete(HttpServletRequest request, HttpServletResponse response) throws IOException {
		Result result = null;
		try {
			String pids = request.getParameter("ids");
			if (pids != null) {
				int deleteCount = demoService.deleteLogicByIds(ConstantsUtil.DELETE_YES, StringUtilss.stringToIntegerArray(pids.split("::")));
				result = new Result(true, "删除成功！操作" + deleteCount + "条数据");
			} else {
				result = new Result(false, "没有参数，非法操作！");
			}
		} catch (Exception e) {
			result = new Result(false, "更新失败！"+e.getMessage());
		} finally {
			JSONUtilss.renderJson(result, response);
		}
		return null;
	}
	
	
	@RequestMapping("index")
	public String index() {
		Demo demo = new Demo();
		demo.setName("demo/index");
		demo.setDeleteFlag(DeleteFlagEnum.NORMAL);
		demoService.insert(demo);
		return "demo/index";
	}
	
	@RequestMapping(value = "/page/{id}")
	public ModelAndView blogItem(@PathVariable("id") Integer id, HttpServletRequest request, HttpServletResponse response) {
		
		logger.debug("XXXXXX");
		logger.info("XXXXXX");
		logger.warn("XXXXXX");
		logger.error("XXXXXX");
		
		Map<String, Object> map = new HashMap<String, Object>();
		
		DemoExample demoExampleForCount = new DemoExample();
		demoExampleForCount.setOrderByClause("id asc");
		
		DemoExample demoExampleForList = new DemoExample();
		demoExampleForList.setOrderByClause("id asc");
		
		int pageNumber = id;
		int pageSize = 1;
		Page page = new Page(PaginationUtil.startValue(pageNumber, pageSize), pageSize);
		demoExampleForList.setPage(page);
		
		Pagination<Demo> pagination = demoService.getPanigationByRowBounds(demoExampleForCount, demoExampleForList);
		
		page.setTotalRecords(pagination.getTotal());
		
		map.put("pagination", pagination);
		map.put("page", page);
		
		ModelAndView mav = new ModelAndView("demo/page", map);

		return mav;
	}
	
	/**
	 * demoService.insert(demo) 进行插入方法，之后插入第二条数据，name字段使用demo.getId()主键内容
	 * 测试关联关系的处理
	 * @return
	 */
	@RequestMapping(value = "insertRel")
	public ModelAndView insertRel() {
		
		Map map = new HashMap();
		
		Demo demo = new Demo();
		demo.setDeleteFlag(DeleteFlagEnum.NORMAL);
		demo.setCreateTime(new Date());
		demo.setName("demo/index");
		demoService.insert(demo);
		
		Demo demo2 = new Demo();
		demo2.setDeleteFlag(DeleteFlagEnum.NORMAL);
		demo2.setCreateTime(new Date());
		demo2.setName(demo.getId() + "");
		demoService.insert(demo2);
		
		ModelAndView mav = new ModelAndView("demo/page", map);

		return mav;
	}
	
	
}
